import { useMemberStore } from '@/stores'

/*
 * @Description:
 * @Author: 稽辉
 * @Date: 2025-01-18 15:51:15
 * @LastEditTime: 2025-03-20 10:25:26
 * @LastEditors: 稽辉
 */
// const baseURL = 'http://localhost:8080'
const baseURL = 'http://192.168.3.30:8080'
// const baseURL = 'https://2930-27-39-221-205.ngrok-free.app'
// const baseURL = 'https://1f3e-27-39-221-205.ngrok-free.app'
// const baseURL = 'https://1bbb-27-39-221-205.ngrok-free.app'
//拦截器添加
const httpInterceptor = {
  //拦截前触发
  invoke(options: UniApp.RequestOptions) {
    //非http类拼接地址
    if (!options.url.startsWith('http')) {
      options.url = baseURL + options.url
    }
    options.timeout = 10000
    //console.log(options)
    //添加小程序端的请求标识
    options.header = {
      ...options.header,
      'source-client': 'miniapp',
      'ngrok-skip-browser-warning': '123',
    }
    //添加token
    const memberStore = useMemberStore()
    const token = memberStore.profile?.token
    if (token) {
      options.header.Authorization = token
    }
  },
}
uni.addInterceptor('request', httpInterceptor)
uni.addInterceptor('uploadFile', httpInterceptor)

//请求函数的封装
interface Data<T> {
  code: string
  message: string
  data: T
}
//添加类型

export const http = <T>(options: UniApp.RequestOptions) => {
  return new Promise<Data<T>>((resolve, reject) => {
    uni.request({
      ...options,
      success(res) {
        //提取核心数据
        //根据状态码处理
        if (res.statusCode >= 200 && res.statusCode < 300) {
          resolve(res.data as Data<T>)
        } else if (res.statusCode === 401) {
          //清理信息，跳转到登陆页
          const memberStore = useMemberStore()
          memberStore.clearProfile()
          uni.navigateTo({ url: '/pages/login/login' })
          reject(res)
        } else {
          uni.showToast({
            title: (res.data as Data<T>).message || '请求错误',
            icon: 'fail',
            mask: true,
          })
        }
      },
      fail(err) {
        uni.showToast({
          title: '网络错误',
          icon: 'fail',
          mask: true,
        })
        reject(err)
      },
    })
  })
}
